import EXIF from 'exif-js';

export default {
  getOrientation: file =>
    new Promise(resolve => {
      EXIF.getData(file, function() {
        const orient = EXIF.getTag(this, 'Orientation');
        resolve(orient);
      });
    }),

  dataURLtoFile: (base64, filename) => {
    const base64Arr = base64.split(',');
    let imgtype = '';
    let base64String = '';

    if (base64Arr.length > 1) {
      // 如果是图片base64，去掉头信息
      base64String = base64Arr[1];
      imgtype = base64Arr[0].substring(base64Arr[0].indexOf(':') + 1, base64Arr[0].indexOf(';'));
    }
    // 将base64解码
    const bytes = atob(base64String);
    // var bytes = base64;
    const bytesCode = new ArrayBuffer(bytes.length);
    // 转换为类型化数组
    const byteArray = new Uint8Array(bytesCode);

    // 将base64转换为ascii码
    for (let i = 0; i < bytes.length; i++) {
      byteArray[i] = bytes.charCodeAt(i);
    }

    // 生成Blob对象（文件对象）
    return new File([bytesCode], filename, {
      type: imgtype,
    });
  },

  rotateImage: (img, width, height, orient) => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    canvas.width = width;
    canvas.height = height;

    // 铺底色
    ctx.fillStyle = '#fff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, width, height);

    switch (orient) {
      case 6:
        canvas.width = height;
        canvas.height = width;
        ctx.rotate(Math.PI / 2);
        ctx.drawImage(img, 0, -height, width, height);
        break;
      case 3:
        ctx.rotate(Math.PI);
        ctx.drawImage(img, -width, -height, width, height);
        break;
      case 8:
        canvas.width = height;
        canvas.height = width;
        ctx.rotate((3 * Math.PI) / 2);
        ctx.drawImage(img, -width, 0, width, height);
        break;
      default:
    }

    return canvas.toDataURL('image/jpeg');
  },
};
